package com.cndym.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.type.TypeReference;

import com.cndym.adapterForMobile.tms.bean.MobileOrderBeanToken;
import com.cndym.cache.XMemcachedClientWrapper;
import com.cndym.service.IFillByYYService;
import com.cndym.utils.DESPlus;
import com.cndym.utils.JsonBinder;
import com.cndym.utils.SpringUtils;
import com.cndym.utils.Utils;

/**
 * @author faxc
 * @date 2014-12-19 下午02:11:33
 */
public class ChangeRequestWarpper extends HttpServletRequestWrapper {
    private HttpServletRequest request;
    private Logger logger = Logger.getLogger(getClass());
    DESPlus dp=null;
    public ChangeRequestWarpper(HttpServletRequest request) {
        super(request);
        this.request = request;
        if(dp==null)
        {
        	try {
				dp=new DESPlus();
			} catch (Exception e) {
				logger.error("", e);
			}
        }
	}
    XMemcachedClientWrapper memcachedClientWrapper = (XMemcachedClientWrapper) SpringUtils.getBean("xmemcachedClientWrapper");
    IFillByYYService fillByYYService = (IFillByYYService) SpringUtils.getBean("fillByYYServiceImpl");
   
    @Override
    public String getParameter(String parameter) {
    	String innerMsg = null;
    	Map<String,String> innerMsgMap = new HashMap<String, String>();
		
    	Map<String, String> paraMap = new HashMap<String, String>();
        String msg = request.getParameter(parameter);
        MobileOrderBeanToken orderBean = null;
        String userCode = "";
        try {
        	paraMap = JsonBinder.buildNormalBinder().getMapper().readValue(msg, new TypeReference<Map<String, String>>() {});
        	innerMsg = paraMap.get("msg");
        	String cmd = paraMap.get("cmd");
        	String func = paraMap.get("func");
        	
        	//八元包中,接受参数异于通常的方法,做特别处理
        	if((cmd.equals("3300") || cmd.equals("3303")) && func.equals("activity"))
        	{
        		try {
        			String json = paraMap.get("msg");
        			Map msgMap = JsonBinder.buildNonDefaultBinder().fromJson(json, Map.class);
        			Map<String, String> tMap = (Map<String, String>)msgMap.get("map");
        			String token = tMap.get("token");
        			
        			if (!Utils.isNotEmpty(token)) {
            			logger.info(cmd+","+func+",no token goback");
           	         	return request.getParameter(parameter);
        			}

        			String res=changeTokenToString(paraMap,token);
        			int resInd=res.indexOf("_");
        			if(resInd < 0)
        			{
        				return res;//错误信息
        			} else {
        				tMap.put("userCode", res.split("_")[1]);
        				tMap.remove("token");
        				String aaaa = JsonBinder.buildNonDefaultBinder().toJson(tMap);
        				Map paraMap1=new HashMap();
        				paraMap1.put("map", tMap);
        				aaaa=JsonBinder.buildNonDefaultBinder().toJson(paraMap1);
        				paraMap.put("msg", aaaa);
        				return JsonBinder.buildNonDefaultBinder().toJson(paraMap);
        			}
        		} catch (Exception e) {
        			logger.error(cmd+","+func, e);
        		}
        	}

        	//需要排除掉的func
        	String[] excludeFunc = new String[]{"lotteryIntro", "iosSubscribe", "subscribe","donate","pay"};
        	if(cmd.equals("3300") && !ArrayUtils.contains(excludeFunc, func))
        	{
        		orderBean = JsonBinder.buildNonDefaultBinder().fromJson(innerMsg, MobileOrderBeanToken.class);
        		if(Utils.isNotEmpty(orderBean.getToken()) )
        		{
        			String token = orderBean.getToken();
        			userCode = memcachedClientWrapper.get(token);

        			String res = changeTokenToString(paraMap,token);
        			int resInd = res.indexOf("_");
        			if(resInd < 0)
        			{
        				return res;//错误信息
        			}

        			userCode = res.split("_")[1];
        			if(token != null)
        			{
        				try {
        					orderBean.setUserCode(userCode);
        					orderBean.setToken(null);
        					String aaaa = JsonBinder.buildNonDefaultBinder().toJson(orderBean);
        					paraMap.put("msg", aaaa);
        					return JsonBinder.buildNonDefaultBinder().toJson(paraMap);
        				} catch (Exception e) {
        					logger.error(cmd+","+func, e);
        				}
        			}
        		}
        	}
        	else
        	{
        		if(Utils.isNotEmpty(innerMsg))
        		{
        			innerMsgMap = JsonBinder.buildNormalBinder().getMapper().readValue(innerMsg, new TypeReference<Map<String, String>>() {});
        		}
        	}
        } catch (Exception e) {
        	logger.error("",e);
        }

        if(innerMsgMap.get("token") != null)
        {
        	String token = innerMsgMap.get("token");
        	String res = changeTokenToString(paraMap, token);
        	int resInd = res.indexOf("_");
        	if(resInd < 0 )
        	{
        		return res;//错误信息
        	}
        	userCode = res.split("_")[1];
        	try {
        		logger.info("转换前token=" + token + ",转换后userCode=" + userCode);
        		innerMsgMap.put("userCode", userCode);
        		innerMsgMap.remove("token");
        		innerMsg=JsonBinder.buildNonDefaultBinder().toJson(innerMsgMap);
        		paraMap.put("msg", innerMsg);
        		return JsonBinder.buildNonDefaultBinder().toJson(paraMap);
        	} catch (Exception e) {
        		logger.error("userCode="+userCode, e);
        	}
        }
        return request.getParameter(parameter);
	}

    public String changeTokenToString(Map map,String token)
    {
    	String userCode="";
    	if(token.length()=="20130224174326355633".length()) //现在有传来的token值为"20130224174326355633"这种类似的情况(实际值为userCode),现在做兼容
    	{
    		if("3104".equals(map.get("cmd"))&&"reset".equals(map.get("func")))
    		{
    			userCode=token;
    			return "success_"+userCode;
    		}
    	}

    	try {
    		userCode = memcachedClientWrapper.get(token);
			if(userCode==null)
			{
				userCode=dp.decrypt(token).split("_")[0];
				if (CheckFrameWriter.IsmemCacheOK) {
					if (memcachedClientWrapper.get(userCode) == null) 
					{
						logger.info(token+"_"+userCode+ "已经过期");
						fillByYYService.updateBySQL("delete from token_usercode_mapping where token=?", new String[]{token});
						fillByYYService.updateBySQL("delete from usercode_token_mapping where user_code=?", new String[]{userCode});
						return "TokenExpires";
					} else {
						logger.info(token+"_"+userCode+  "在另外设备登录");
						fillByYYService.updateBySQL("delete from token_usercode_mapping where token=?", new String[]{token});
						return "LoginOnOtherMachine";
					}
				}
				else
				{
					logger.warn("memCache挂了,只能去数据库查询token存不存在了: "+token);
					List list=fillByYYService.getListBySQL("select*From token_usercode_mapping where token=?", new String[]{token});
					if(list.size()==0)
					{
						logger.info(token+"_"+userCode+ "已经过期");
						fillByYYService.updateBySQL("delete from usercode_token_mapping where user_code=?", new String[]{userCode});
						return "TokenExpires";
					}
					list=fillByYYService.getListBySQL("select*From usercode_token_mapping where user_code=?", new String[]{userCode});
					if(list.size()>0)
					{
						logger.info(token+"_"+userCode+  "在另外设备登录");
						fillByYYService.updateBySQL("delete from token_usercode_mapping where token=?", new String[]{token});
						return "LoginOnOtherMachine";
					}
				}
			}
		} catch (Exception e) {
			logger.error(token, e);
		}
    	return "success_"+userCode;
    }
}

